<?php

require_once('database.php');

class UserAuth {
    var $_db=null; 
    var $userid=null;
    var $username=null;
    var $usercookie=null;
    var $sessioncookie=null;
    var $session_id=null;
    function UserAuth(&$db) {
		$this->_db =& $db;
     
    
    }
    function Login($user,$pass){
		if (!$user || !$pass) {            
		  return FALSE;
		}

		$this->_db->setQuery( "SELECT * "
    		. "\nFROM user "
    	   	. "\nWHERE username='$user' AND password='$pass' and status='active'"
		);
		$row = null;
		if (!$this->_db->loadObject( $row )) { 		
		  return FALSE;
		}
		
		if (defined( '_ACL_ADMIN' )) {
            if ($row->vip!='1') return FALSE;
		}
		$lifetime = time() + 365*24*60*60;
		setcookie( "usercookie[username]", $user, $lifetime, "/" );
		setcookie( "usercookie[id]", $row->id, $lifetime, "/" ); 		
        $this->initSession();
        
		$this->_db->setQuery( "update session "
    		. "\n set "
    		. "\n  userid='$row->id',"
    		. "\n  sess_start=now(),"
    		. "\n  sess_expire=DATE_ADD(now(),INTERVAL ".(_DEFAULT_TIMEOUT)." MINUTE),"
    		. "\n  last_activity=now(),"
    		. "\n  ip='".$_SERVER['REMOTE_ADDR']."',"
    		. "\n  user_agent='".$_SERVER['HTTP_USER_AGENT']
            . "' where  session='$this->session_id'"
		); 
		$this->_db->query();
        $this->userid=$row->id; 
        $this->username=$user; 
        $this->usercookie['username']=$user; 
        $this->usercookie['id']=$row->id; 
        return TRUE;
		
    }
    function Logout(){
        if ($this->Check_Auth()) {
    		$this->_db->setQuery( "delete from session  where  session='$this->session_id'"); 
    		$this->_db->query();
            
        }
		setcookie( "usercookie[username]", "", time() - 36000, "/" );
	   	setcookie( "usercookie[id]", "", time() - 36000, "/" ); 		
        setcookie( "sessioncookie", "", time() - 36000, "/" );
          
    }
	function generateId() {
		$failsafe = 20;
		$randnum = 0;
		while ($failsafe--) {
			$randnum = md5( uniqid( microtime(), 1 ) );
			if ($randnum != "") {
				$cryptrandnum = md5( $randnum );
				$this->_db->setQuery( "SELECT * FROM session WHERE session=MD5('$randnum')" );
				if(!$result = $this->_db->query()) {
					die( $this->_db->stderr( true ));
					// todo: handle gracefully
				}
				if ($this->_db->getNumRows($result) == 0) {
					break;
				}
			}
		}
		$this->sessioncookie = $randnum;
		$this->session_id = md5( $randnum . $_SERVER['REMOTE_ADDR'] );
	} 
    
	function initSession() {

		$sessioncookie = GetParam( $_COOKIE, 'sessioncookie', null );
        $sess=md5( $sessioncookie . $_SERVER['REMOTE_ADDR'] );
        
		$row = null;
        $this->_db->setQuery("select * from session where session='$sess'");
        
		if ($this->_db->loadObject( $row )) {
			// Session cookie exists, update time in session table
            $this->_db->setQuery("update session set last_activity=now(), ".
                "sess_expire=DATE_ADD(now(),INTERVAL ".(_DEFAULT_TIMEOUT)." MINUTE) where session='$sess'");
			$this->_db->query();
			$this->sessioncookie=$sessioncookie;
			$this->session_id=$row->session;
		} else {
			$this->generateId();
			setcookie( "sessioncookie", $this->sessioncookie, time() + 43200, "/" );
            $this->_db->setQuery("insert into session set last_activity=now(), session='$this->session_id',".
                "sess_expire=DATE_ADD(now(),INTERVAL ".(_DEFAULT_TIMEOUT)." MINUTE)  ");
			$this->_db->query();

		}
	}
    function Check_Auth(){
		$sess = GetParam( $_COOKIE, 'sessioncookie', null );
		$ucookie = GetParam( $_COOKIE, 'usercookie', null );
        $sess=md5( $sess . $_SERVER['REMOTE_ADDR'] );
        
        $this->_db->setQuery("delete from session where now()>sess_expire"); //PURGE SESSION
        $this->_db->query();
        
		$row = null;
        $this->_db->setQuery("select * from session a left join user b 
            on a.userid=b.id where session='$sess'");
        
		if (!$this->_db->loadObject( $row )) {
	       return FALSE;
        }
        if (($row->id==$ucookie['id'])&&($row->username==$ucookie['username'])
            &&($_SERVER['REMOTE_ADDR']==$row->ip)){
            //authenticated ok
    	  if (defined( '_ACL_ADMIN' )) {
                if ($row->vip!='1') return FALSE;
    	  }
          $this->userid=$row->id; 
		  $this->username=$row->username; 
          $this->usercookie['username']=$row->username; 
          $this->usercookie['id']=$row->id; 
    	  $this->sessioncookie = GetParam( $_COOKIE, 'sessioncookie', null );
		  $this->session_id = $sess;
		  if (!defined(_TIMEOUT_ABSOLUTE)){
				$this->_db->setQuery("update session set last_activity=now(), ".
					"sess_expire=DATE_ADD(now(),INTERVAL ".(_DEFAULT_TIMEOUT)." MINUTE) where session='$sess'");
				$this->_db->query();
		  
		  }else{
				$this->_db->setQuery("update session set last_activity=now()  where session='$sess'");
				$this->_db->query();
		  }
 	       return TRUE;
        }else{
	       return FALSE;
        }
    }
}

function GetParam( &$arr, $name, $def=null ) {
	$return = null;
	if (isset( $arr[$name] )) {
		return $arr[$name];
	} else {
		return $def;
	}

} 
     
?>
